package it.lolled.core;

import it.lolled.entity.Post;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * Hello world!
 *
 */
public class App9GAG {
	public static void main(String[] args) {
		new App9GAG().work();
	}

	public void work() {

		Document doc;
		try {

			// need http protocol
			doc = Jsoup.connect("http://9gag.com").get();

			List<Post> postList = new LinkedList<Post>();
			HttpSend httpSend = new HttpSend();

			// get all links
			Elements postElements = doc.select(".badge-entry-entity");
			for (Element postElement : postElements) {
				try {
					String id = postElement.attr("data-entry-id");
					String title = postElement.getElementsByClass("badge-item-title").get(0).getElementsByTag("a")
						.get(0).html();

					String imageUrl = "";
					if (postElement.getElementsByClass("badge-item-img").size() > 0) {
						imageUrl = postElement.getElementsByClass("badge-item-img").get(0).attr("src");
					}

					String gifUrl = "";
					if (postElement.getElementsByClass("badge-animated-container-animated").size() > 0) {
						gifUrl = postElement.getElementsByClass("badge-animated-container-animated").attr("data-image");
					}

					if (!"".equals(gifUrl) || !"".equals(imageUrl)) {
						postList.add(new Post(id, title, "".equals(gifUrl) ? imageUrl : gifUrl, "9gag"));
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			for (Post post : postList) {
				System.out.println(post.getInsert());
				httpSend.postInsert(post);

			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
